import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/model/collection_model/first_publish_buy_order_model.dart';
import 'package:yysk_app/model/market_model/market_batch_sale_list_model.dart';
import 'package:yysk_app/model/market_model/market_batch_sale_list_order_model.dart';
import 'package:yysk_app/model/order_model/get_pay_token_model.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/nft_pages/order/order_page.dart';
import 'package:yysk_app/pages/nft_pages/pay_pages/confirm_payment/confirm_payment_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_exchange_psw.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';

class MarketCollectionBuyController extends GetxController {
  var title = '批量购买'.obs;
  var type = '0'.obs; //0 不是批量出售 1是批量
  var id = '0'.obs; //列表id
  var num = '0'.obs; //
  var orderBy = 'asc'.obs; //
  var incubationId = '0'.obs;
  // var list = RxList<dynamic>([{},{}]);
  var saleList = RxList<MarketBatchSaleListModelItem>([]);
  var saleListChoose = RxList<MarketBatchSaleListModelItem>([]);
  var totalPrice = '0'.obs;
  var isBatch = false.obs;
  var canBuyCount = '0'.obs;
  var count = 0.obs;
  final ScrollController scrollController = ScrollController();
  var total = 0.obs;

  //相关公告
  int pageNum = 1;
  int math = 1000000;
  @override
  void onInit() {
    super.onInit();
    canBuyCount.value =
        Get.parameters['canBuyCount'] ?? Get.arguments['canBuyCount'];
    id.value = Get.parameters['id'] ?? Get.arguments['id'];
    incubationId.value =
        Get.parameters['incubationId'] ?? Get.arguments['incubationId'];
    getList();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getList(loadMore: true);
      }
    });
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
  }

  Future<void> handleRefresh() async {
    // list.add({});
    totalPrice.value = '0';
    orderBy.value = 'asc';
    saleListChoose.value = [];
    getList();
  }

  //列表

  Future<void> getList({loadMore = false}) {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    try {
      return http.netFetch<MarketBatchSaleListModel>(
        ProductApi.getSaleOrderPage,
        method: Method.post,
        params: {
          'pageNum': pageNum,
          'pageSize': 20,
          'collectionId': id.value,
          'saleType': 'INCUBATION',
          'orderBy': orderBy.value,
        },
        success: (result) {
          total.value = result.data?.total ?? 0;
          List<MarketBatchSaleListModelItem> items = result.data?.list ?? [];

          if (loadMore && items.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            saleList.clear();
          }
          saleList.addAll(items);
        },
      );
    } catch (e) {
      debugPrint(e.toString());
      if (loadMore) {
        pageNum--;
      }
      return Future.error(e);
    }
  }

  //出售的列表数据
  Future<void> chooseListUnSell(dynamic id) async {
    for (var element in saleList) {
      if (element.id == id) {
        element.isSelect = !element.isSelect;
      }
    }
    count++;
    saleListChoose.value = [];
    dynamic price = 0;
    for (var element in saleList) {
      if (element.isSelect == true) {
        saleListChoose.add(element);
        price = price + (element.salePrice) * math;
      }
    }
    totalPrice.value = (price / math).toString();
  }

  // 创建批量孵化订单
  createFirstOrder({String idOne = ''}) {
    List<String> listChoose = [];
    for (var element in saleListChoose) {
      listChoose.add('${element.id}');
    }
    if (idOne != '') {
      listChoose = [idOne];
    }
    http.netFetch<MarketBatchSaleListOrderModel>(
      ProductApi.batchCreateIncubationOrder,
      params: {
        'collectionId': id.value,
        'incubationId': incubationId.value,
        'saleOrderIds': listChoose,
      },
      success: (r) {
        if (r.code == 200 && r.data!.noPay == false) {
          // getPayToken(r.data!.orderId);
          List<String> list = [];
          for (var element in (r.data!.orderDetails!)) {
            list.add(element.orderId!);
          }
          getPayToken(list);
        } else {
          _toPayWaitOrder(context: Get.context!, res: r.data!);
        }
      },
      fail: (code, message) {
        // 被锁单 刷新列表重新选择
        if (code == '80058') {
          getList();
        }
      },
    );
  }

  //待支付订单
  _toPayWaitOrder({
    required BuildContext context,
    required MarketBatchSaleListOrderModel res,
  }) async {
    await showConfirmDialog(
      context: context,
      message: '无法下单,您有未支付订单待处理',
      messages: [],
      actions: [
        ActionModel(
          label: '取消',
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
          onPressed: () {},
        ),
        ActionModel(
          label: '立即处理',
          onPressed: () {
            Get.toNamed(
              '${OrderPage.path}?productType=${res.productType}&jumpTab=incubation',
              arguments: {
                'productType': res.productType,
                'jumpTab': 'incubation',
              },
            );
          },
        ),
      ],
    );
  }

  //获取令牌
  Future<dynamic> getPayToken(List<String> list) async {
    try {
      http.netFetch<GetPayTokenModel>(
        ProductApi.batchGetPayToken,
        method: Method.post,
        params: {"businessType": 'INCUBATE', 'orderIds': list},
        success: (result) {
          Get.toNamed(
            '${ConfirmPaymentPage.path}?cashierToken=${result.data?.cashierToken}&accessToken=${result.data?.accessToken}&businessType=INCUBATE&clientType=web',
            arguments: {
              'cashierToken': result.data?.cashierToken,
              'accessToken': result.data?.accessToken,
              'businessType': 'INCUBATE',
              'buynow': '1',
            },
          );
          return result;
        },
      );
    } catch (e) {
      consoleLog(e.toString());
    }
  }

  Future<bool> isSm() async {
    final GlobalController globalController = Get.find();
    if (globalController.user.value!.isSm != true) {
      showConfirmDialog(
        context: Get.context!,
        fontSize: 16,
        message: '请先完成实名认证',
        actions: [
          ActionModel(
            label: '取消',
            colorStart: AppColors.backgroundColorGreyF8,
            colorEnd: AppColors.backgroundColorGreyF8,
            fontColor: AppColors.fontColor,
          ),
          ActionModel(
            label: '立即认证',
            onPressed: () {
              Get.toNamed(SettingRealNameAuthPage.path);
            },
          ),
        ],
      );
      return false;
    } else {
      if (globalController.user.value?.transactionPassword == null) {
        isSetPayPassword();
        return false;
      } else {
        return true;
      }
    }
  }

  //是否开通交易密码
  Future<dynamic> isSetPayPassword() async {
    try {
      showConfirmDialog(
        context: Get.context!,
        message: '请先设置交易密码',
        messages: [],
        fontSize: 16,
        actions: [
          ActionModel(label: '取消', onPressed: () {}),
          ActionModel(
            label: '前往设置',
            onPressed: () {
              Get.toNamed(ChangeExchangePassword.path);
            },
          ),
        ],
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  chooseAll() {
    saleListChoose.value = [];
    for (var element in saleList) {
      if (element.status == 'NORMAL' && element.isMyself == false) {
        element.isSelect = false;
      }
    }
    int num = 0;
    consoleLog('11111188888888');
    for (var element in saleList) {
      if (element.status == 'NORMAL' &&
          num < 10 &&
          num < int.parse(canBuyCount.value) &&
          element.isMyself == false) {
        element.isSelect = true;
        num++;
      }
    }
    dynamic price = 0;
    for (var element in saleList) {
      if (element.isSelect == true) {
        saleListChoose.add(element);
        price = price + (element.salePrice) * math;
      }
    }
    totalPrice.value = (price / math).toString();
    count++;
  }
}
